(function(){
socket = {
 host: document.location.host.split(':')[0],
 port: document.location.host.split(':')[1] || '',
 path: document.location.pathname,
 
 loaded: function(){
  this.flash = document.getElementById("myflash");
  this.connect(this.host, this.port);
 },
 connected: function(){
  this.handshake(this.path);
  $('broswer_socket_status').value=1;
 },
 security_error: function(msg){},								
 disconnected: function(){$('broswer_socket_status').value=0;},
 io_error: function(msg){},						
 receive:function(msg){
  eval(msg);
 },
 
 connect: function(server, port){this.flash.connect(server, port);},
 write: function(msg){this.flash.write(msg+'\n');},
 close: function(){this.flash.close();},
 handshake: function(path){
  this.write('GET ' + path+'/__ws__' + ' HTTP/1.1');
  this.write('Host:' + this.host+':'+this.port);
  this.write('');    
 }
};

open_socket=function(){swfobject.embedSWF(
 'style/flashsocket/socket_bridge.swf', 'myflash', '1000', '600', '9','style/flashsocket/expressInstall.swf',
 {scope:'socket'}, 
 {allowscriptaccess:'always',allownetworking:'all'}
);}
open_socket();

/*
 * \x01 Number; \x02 String; \x03 Array; \x04 Dict
 */
wsubmit=function(array, obj, callback){
 array[0] = document.location.host+array[0];
 if($('broswer_socket_status').value==0){
  socket.connect(socket.host, socket.port);
  socket_t = setTimeout(function(){wsubmit(array, obj, callback)}, 1500);
 }else{
 var send_list=function(array){
  var len=array.length;
  socket.write(len);
  for(var i=0;i<len;i++){
   _send(array[i])
  }
 }
 
 var send_dict=function(obj){
  var len=get_obj_len(obj);
  socket.write(len);
  for(var i in obj){
   _send(i);
   _send(obj[i]);
  }
 }
 
 var _send=function(obj){
  switch(obj.constructor){
   case Number:
    socket.write('\x01')
    socket.write((''+obj).length)
    socket.write(obj)
    break;
   case String:
    socket.write('\x02')
    socket.write(obj.length)
    socket.write(obj)
    break;
   case Array:
    socket.write('\x03')
    send_list(obj)
    break;
   case Object:
    socket.write('\x04')
    send_dict(obj)
    break;
  }
 }

 var get_obj_len=function(o){
  var i, count = 0;
  for(i in o){
   if(o.hasOwnProperty(i))
    count++;
  }
  return count;
 }

 send_list(array);
 send_dict(obj);
 }
}

})();
